import './global.scss';
import React, { useEffect } from 'react';
import { AppStore } from '../store';
import { Empty } from '../components/empty';
import { AppForm } from './AppForm';
import { slave } from '../slave';
import { AppModelService, GenerateService, SelectParamService } from '@manycore/pages-vm-api';

function App() {
  const { appState, updateAppModeState, updateGenerateFormState, updateSelectedModelState, updateEditFormState } =
    AppStore.useContainer();

  useEffect(() => {
    // 监听模式的切换逻辑
    const service = slave.getService(AppModelService);
    // 监听事件，并更新配置
    service!.appMode.on((option) => {
      updateAppModeState(option);
    });
    // 获取当前配置信息
    service?.getCurrentOption().then((option) => {
      updateAppModeState(option);
    });

    // 初始化模生成的表单
    const generateService = slave.getService(GenerateService)!;
    generateService.getGenerateFormFields().then((form) => {
      updateGenerateFormState(form);
    });

    // 处理小程序中，编辑五金参数
    const selectParamService = slave.getService(SelectParamService)!;
    selectParamService.selectedParameters.on(updateEditFormState);
    selectParamService.getParameters().then(updateEditFormState);

    // 预览图处理逻辑
    /*const imageService = slave.getService(SketchImageService)!;
        imageService.getCurrentImageUrl().then(updateSketchImageState);
        imageService.sketchImage.on(updateSketchImageState);*/

    const appModelService = slave.getService(AppModelService)!;
    appModelService.getCurrentSelectedModelCount().then((count) => updateSelectedModelState(count > 0));
    appModelService.selectedModelCount.on((count) => updateSelectedModelState(count > 0));
  }, []);

  /*    const toggle = (
        <div
            style={{ position: 'absolute', top: 400, left: 0 }}
        >
            <div>{JSON.stringify(appState, null, 2)}</div>
        </div>
    );*/

  if (appState.hasSelected) {
    return <AppForm />;
  }

  return <Empty />;
}

export default function AppRoot() {
  return (
    <AppStore.Provider>
      <App />
    </AppStore.Provider>
  );
}
